//
//  TravelDetailViewController.m
//  TeamProject_Travel
//
//  Created by lanou3g on 16/3/25.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "TravelDetailViewController.h"
#import "OneTravelDetailsCell.h"
#import "TwoTravelDetailsCell.h"
#import "ThreeTravelDetailsCell.h"
#import "UINavigationBar+Awesome.h"
#import "CDHttpHelper.h"
#import "SKModel.h"
#import "DetailsModel.h"
#import "UIImageView+WebCache.h"
#import "Singleton.h"

#define NAVBAR_CHANGE_POINT 50

@interface TravelDetailViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong)UITableView * tableView;
@property(nonatomic,assign)NSInteger days;
@property(nonatomic,strong)NSMutableArray *keyArray;
@end

@implementation TravelDetailViewController

//- (void)viewWillAppear:(BOOL)animated
//{
//    [self.navigationController setNavigationBarHidden:YES];
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    self.automaticallyAdjustsScrollViewInsets = NO;

    self.tableView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    
    //初始化数组
    self.allDataArray = [NSMutableArray array];
    
    
    //注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"OneTravelDetailsCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"One"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TwoTravelDetailsCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"Two"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ThreeTravelDetailsCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"Three"];
    
    //    self.tableView.estimatedRowHeight = 600;
    
    //解析数据
    [self handleData];
    
    [self.navigationController.navigationBar lt_setBackgroundColor:[UIColor clearColor]];
    
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}


- (void)handleData{
    // 从前往后传id
    Singleton *single = [Singleton shareSingle];
    
    
    [[CDHttpHelper defaultCDHttpHelper] get:[NSString stringWithFormat:@"https://chanyouji.com/api/trips/%ld.json",single.ID] params:nil success:^(id responseObj) {
        NSError *error = nil;
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:&error];
        
        // 直接赋值
        self.name = dictionary[@"name"];
        self.photos_count = [dictionary[@"photos_count"] intValue];
        self.start_date = dictionary[@"start_date"];
        self.end_date = dictionary[@"end_date"];
        
        // 获取大图
        self.front_cover_photo_url = dictionary[@"front_cover_photo_url"];
        
        // 获取个人头像
        NSDictionary *dict = dictionary[@"user"];
        self.image = dict[@"image"];
        
        // 获取详细信息
        for (NSDictionary *diction in dictionary[@"trip_days"]) {
            for (NSDictionary *dict in diction[@"nodes"]) {
                for (NSDictionary *dic in dict[@"notes"]) {
                    
                    // 获取文字
                    DetailsModel *model = [[DetailsModel alloc]init];
                    [model setValuesForKeysWithDictionary:dic];
                    
                    // 获取图片
                    for (NSString *key in dic) {
                        if ([key isEqualToString:@"photo"]) {
                            NSDictionary *dic11 = dic[@"photo"];
                            [model setValuesForKeysWithDictionary:dic11];
                        }
                    }
                    [self.allDataArray addObject:model];
                }
            }
        }
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.allDataArray.count;
}

// tableHeaderView
- (void)tableViewheaderView
{
    // 图片
    UIImageView *headImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, self.tableView.frame.size.height / 3)];
    [headImage sd_setImageWithURL:[NSURL URLWithString:self.front_cover_photo_url]];
    
    // 标题
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.tableView.frame.size.width / 6,self.tableView.frame.size.height * 2 / 9, self.tableView.frame.size.width * 3 / 4, self.tableView.frame.size.height / 28)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.text = self.name;
    titleLabel.textColor = [UIColor whiteColor];
    [titleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:20]];
    [headImage addSubview:titleLabel];
    
    // 副标题
    UILabel *subheadLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.tableView.frame.size.width / 6,self.tableView.frame.size.height * 4 / 15, self.tableView.frame.size.width * 3 / 4, self.tableView.frame.size.height / 28)];
    subheadLabel.backgroundColor = [UIColor clearColor];
    
    if (self.detailModel.start_date != nil) {
        subheadLabel.text = [NSString stringWithFormat:@"%@ | %ld天, %ld张图片",self.detailModel.start_date,(long)self.detailModel.days,self.photos_count];
    }else{
        
        subheadLabel.text = [NSString stringWithFormat:@"%ld天, %ld张图片",(long)self.detailModel.days,self.photos_count];
    }
    
    subheadLabel.textColor = [UIColor whiteColor];
    [headImage addSubview:subheadLabel];
    
    // 头像
    UIImageView *headPortraitView = [[UIImageView alloc]initWithFrame:CGRectMake(self.tableView.frame.size.width / 25, CGRectGetMinY(titleLabel.frame), self.tableView.frame.size.width / 9, CGRectGetHeight(titleLabel.frame) + CGRectGetHeight(subheadLabel.frame))];
    [headPortraitView sd_setImageWithURL:[NSURL URLWithString:self.image]];
    
    // 头像白底
    UIView *whiteView = [[UIView alloc]initWithFrame:CGRectMake(CGRectGetMinX(headPortraitView.frame) - 2, CGRectGetMinY(headPortraitView.frame) - 2, CGRectGetWidth(headPortraitView.frame) + 4, CGRectGetHeight(headPortraitView.frame) + 4)];
    whiteView.backgroundColor = [UIColor whiteColor];
    
    [headImage addSubview:whiteView];
    [headImage addSubview:headPortraitView];
    
    // 切圆角
    whiteView.layer.cornerRadius = 5;
    whiteView.layer.masksToBounds = YES;
    headPortraitView.layer.cornerRadius = 5;
    headPortraitView.layer.masksToBounds = YES;
    
    self.tableView.tableHeaderView = headImage;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // headerView
    [self tableViewheaderView];
    
    DetailsModel *model = [[DetailsModel alloc]init];
    model = self.allDataArray[indexPath.row];
    
    // 有图有文字
    if (model.Description != nil && model.url != nil) {
        OneTravelDetailsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"One" forIndexPath:indexPath];
        if (cell == nil) {
            cell = [[OneTravelDetailsCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"One"];
        }
        // 设定cell点击不变色
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        [cell.picView sd_setImageWithURL:[NSURL URLWithString:model.url]];

        [cell.picView setContentScaleFactor:[[UIScreen mainScreen] scale]];
        cell.picView.contentMode =  UIViewContentModeScaleAspectFill;
        cell.picView.clipsToBounds  = YES;
        cell.picView.layer.cornerRadius = 4;
        cell.picView.layer.masksToBounds = YES;
        
        cell.descriptionLabel.text = model.Description;
        // 自适应高度
        cell.descriptionLabel.frame = CGRectMake(CGRectGetMinX(cell.descriptionLabel.frame), CGRectGetMinY(cell.descriptionLabel.frame), CGRectGetWidth(cell.descriptionLabel.frame), [self getTrueHeightWithDescription:model.Description]);
        
        return cell;
        
        // 没文字有图
    } else if(model.Description == nil && model.url != nil){
        TwoTravelDetailsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Two" forIndexPath:indexPath];
        if (cell == nil) {
            cell = [[TwoTravelDetailsCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"Two"];
        }
        // 设定cell点击不变色
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        [cell.picView sd_setImageWithURL:[NSURL URLWithString:model.url]];
        cell.picView.layer.cornerRadius = 4;
        cell.picView.layer.masksToBounds = YES;
        
        return cell;
        
        // 有文字没图
    }else{
        ThreeTravelDetailsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Three" forIndexPath:indexPath];
        if (cell == nil) {
            cell = [[ThreeTravelDetailsCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"Three"];
        }
        // 设定cell点击不变色
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.descriptionLabel.text = model.Description;
        
        cell.descriptionLabel.frame = CGRectMake(CGRectGetMinX(cell.descriptionLabel.frame), CGRectGetMinY(cell.descriptionLabel.frame), CGRectGetWidth(cell.descriptionLabel.frame), [self getTrueHeightWithDescription:model.Description]);
        
        return cell;
    }
}

// 自适应高度
- (CGFloat)getTrueHeightWithDescription:(NSString *)discuss
{
    CGRect rect = [discuss boundingRectWithSize:(CGSizeMake([UIScreen mainScreen].bounds.size.width, 200000)) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil];
    return rect.size.height;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    DetailsModel *model = [[DetailsModel alloc]init];
    model = self.allDataArray[indexPath.row];
    
    if (model.Description != nil && model.url != nil) {
        return [self getTrueHeightWithDescription:model.Description] + 40 + 350 + 100;
    }else if(model.Description == nil && model.url != nil){
        return 350;
    }else{
        return [self getTrueHeightWithDescription:model.Description] + 40 + 40;
    }
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    UIColor * color = [UIColor colorWithRed:0 green:191/255.0 blue:255/255.0 alpha:1];
    CGFloat offsetY = scrollView.contentOffset.y;
    if (offsetY > NAVBAR_CHANGE_POINT) {
        CGFloat alpha = MIN(1, 1 - ((NAVBAR_CHANGE_POINT + 64 - offsetY) / 64));
        [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:alpha]];
    } else {
        [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:0]];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [self scrollViewDidScroll:self.tableView];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar lt_reset];
}



@end
